package com.supply.service.impl;

import com.supply.global.Constants;
import com.supply.mapper.LeaveBillMapper;
import com.supply.mapper.ProcurementBillMapper;
import com.supply.pojo.ProcurementBill;
import com.supply.req.ProcurementBillGroup;
import com.supply.service.ProcurementProcessService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ProcurementProcessServiceImpl implements ProcurementProcessService {
    @Autowired
    private ProcurementBillMapper procurementBillMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;


    @Override
    public int startProcurement(ProcurementBillGroup procurementBillGroup) {
        //插入采购单数据，并获得回填Id
        int insertRs = procurementBillMapper.insert(procurementBillGroup);
        System.out.println("插入后回填的数据：" + procurementBillGroup.getId());

        String key = Constants.PROCUREMENT_KEY;
        //构建businessKey，该字段可以记录流程实例关联的采购单的Id，并且该字段是唯一标识
        String businessKey = key + "." + procurementBillGroup.getId();
        //设置该流程的审核人
        Map<String,Object> map = new HashMap<>();
        map.put("buyer",procurementBillGroup.getUserId().toString());
        map.put("personnelman",procurementBillGroup.getPersonnelman());
        map.put("manger",procurementBillGroup.getManger());
        //开启流程
        runtimeService.startProcessInstanceByKey(key,businessKey,map);
        return insertRs;
    }

    @Override
    public ProcurementBill queryProcurementBillByTaskId(String taskId) {
        //根据taskId查询task任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //根据从task任务获取的processInstanceId获取流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId())
                .singleResult();
        //从流程实例中获取businessKey，进而获取采购单Id
        String id = processInstance.getBusinessKey().split("\\.")[1];
        return procurementBillMapper.selectByPrimaryKey(Long.parseLong(id));
    }
}
